package com.danbay.cloud.device.service.electricmeter;

import com.danbay.cloud.device.api.dto.electricmeter.EmRecordReportDto;
import com.danbay.cloud.device.api.service.electricmeter.IEmConsumptionService;
import com.danbay.cloud.device.api.service.electricmeter.IEmRecordService;
import com.danbay.cloud.device.entity.electricmeter.EmRecord;
import com.danbay.cloud.device.entity.electricmeter.EmRecordQuantity;
import com.danbay.cloud.device.mapper.electricmeter.EmRecordMapper;
import com.danbay.cloud.device.mapper.electricmeter.EmRecordQuantityMapper;
import com.danbay.framework.utils.DateUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class EmRecordService implements IEmRecordService {

    @Autowired
    private EmRecordMapper emRecordMapper;

    @Autowired
    private EmRecordQuantityMapper emRecordQuantityMapper;

    @Autowired
    private IEmConsumptionService emConsumptionService;

    @Override
    public int report(EmRecordReportDto reportDto) {
        Date date = new Date();
        int type = reportDto.getType();
        if (0 == type) {//电量
            EmRecordQuantity emRecordQuantity = EmRecordQuantity.builder()
                    .deviceId(reportDto.getDeviceId())
                    .meterCount(reportDto.getValue() / 100D)
                    .reportTime(Long.parseLong(DateFormatUtils.format(date, DateUtils.YMDHMS2)))
                    .addTime(date)
                    .build();
            int isSuccess = emRecordQuantityMapper.insert(emRecordQuantity);
            if(isSuccess > 0) {
                //插入成功之后，算用电明细
                
            }
            return isSuccess;
        } else {
            double divisor = 0;
            if (1 == type) {
                //电压
                divisor = 10D;
            } else if (2 == type) {
                //电流
                divisor = 1000D;
            } else if (3 == type) {
                //功率
                divisor = 1000D;
            } else if (4 == type) {
                //功率因数
                divisor = 1000D;
            }
            EmRecord emRecord = EmRecord.builder()
                    .deviceId(reportDto.getDeviceId())
                    .meterCount(reportDto.getValue() / divisor)
                    .type(type)
                    .addTime(date)
                    .build();
            return emRecordMapper.insert(emRecord);
        }
    }

    @Override
    public double firstRecodeOfLastHour(Date date) {
        return 0;
    }
}
